package com.witdata.common.util;

import com.witdata.common.domain.Status;
import com.witdata.common.exception.GlobalException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
@RequiredArgsConstructor
@Slf4j
public class IdUtils {
    private final HttpServletRequest request;
    private static SnowflakeUtils snowflakeUtils;

    public Long getUserIdByRequest() {
        return getUserIdByRequest(request);
    }

    public static Long getUserIdByRequest(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (ObjectUtils.isEmpty(userId)) {
            log.error("userId = {}", userId);
            throw new GlobalException(Status.TOKENFAILURE);
        }
        return userId;
    }

    public static Long createId() {
        return snowflakeUtils.nextId();
    }

    public void setSnowflakeUtils(SnowflakeUtils snowflakeUtils) {
        IdUtils.snowflakeUtils = snowflakeUtils;
    }
}
